<template>
    <TManageLayout @navigate="handleNavigation">
        <div class="timeline-container">
            <div class="content-wrapper">
                <!-- 左侧时间轴区域 -->
                <div class="left-section">
                    <TimeLine
                        :courseId="courseManageId"
                        :steps="localSteps"
                        @step-toggle="handleStepToggle"
                    />
                    <!-- 添加保存按钮圆球 -->
                    <div
                        class="save-bubble"
                        :class="{ 'show': hasUnsavedChanges }"
                        @click="handleSaveClick"
                    >
                        <span class="save-text">保存</span>
                    </div>
                </div>

                <!-- 右侧步骤编辑区域 -->
                <div class="right-section">
                    <div class="steps-editor">
                        <h1 class="main-title">课程教学计划</h1>
                        <h2 class="editor-title">编辑步骤</h2>

                        <!-- 添加可滚动的步骤列表容器 -->
                        <div class="steps-container">
                            <div class="steps-list">
                                <!-- 步骤列表内容 -->
                                <div v-for="(step, index) in localSteps" :key="index" class="step-item">
                                    <div class="step-number">{{ index + 1 }}</div>
                                    <!-- 第一步和最后一步使用固定文本 -->
                                    <template v-if="index === 0 || index === localSteps.length - 1">
                                        <input
                                            :value="index === 0 ? '上课' : '下课'"
                                            class="step-input"
                                            disabled
                                        />
                                    </template>
                                    <!-- 中间步骤使用下拉框 -->
                                    <template v-else>
                                        <el-select
                                            v-model="step.content"
                                            class="step-select"
                                            filterable
                                            :placeholder="'请选择步骤内容'"
                                            @change="handleStepChange(step)"
                                            popper-class="step-select-dropdown"
                                        >
                                            <el-option
                                                v-for="(option, idx) in stepOptions"
                                                :key="idx"
                                                :label="option"
                                                :value="option"
                                            />
                                            <el-option value="自定义" label="自定义" class="custom-option">
                                                <div class="custom-option-content">
                                                    <span class="custom-label">自定义：</span>
                                                    <el-input
                                                        v-model="step.customContent"
                                                        placeholder="请输入自定义内容"
                                                        @click.stop
                                                        @blur="handleCustomInput(step)"
                                                        @keyup.enter="handleCustomInput(step)"
                                                        @input="handleInput(step)"
                                                        class="custom-input"
                                                    />
                                                </div>
                                            </el-option>
                                        </el-select>
                                    </template>
                                    <!-- 只有中间步骤可以删除 -->
                                    <button
                                        v-if="index !== 0 && index !== localSteps.length - 1"
                                        @click="removeStep(index)"
                                        class="delete-btn"
                                    >×</button>
                                </div>
                            </div>
                        </div>

                        <!-- 固定在底部的按钮组 -->
                        <div class="bottom-actions">
                            <button @click="addStep" class="add-btn">添加步骤</button>
                            <button @click="startClass" class="start-btn" :disabled="!localSteps.length">开始上课</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 使用 Element Plus 的提示弹窗 -->
        <el-dialog
            v-model="showSaveDialog"
            width="30%"
            :show-close="true"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            align-center
        >
            <template #header>
                <div class="dialog-header">
                    <span>提示</span>
                </div>
            </template>
            <div class="save-reminder">
                请先保存当前修改
            </div>
        </el-dialog>

        <!-- 计划名称输入弹窗 -->
        <el-dialog
            v-model="showNameDialog"
            title="请输入计划名称"
            width="30%"
            center
            :close-on-click-modal="false"
            :close-on-press-escape="false"
        >
            <el-input
                v-model="planName"
                placeholder="请输入计划名称"
                @keyup.enter="handleSave"
            ></el-input>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showNameDialog = false">取消</el-button>
                    <el-button type="primary" @click="handleSave">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 确认开始上课弹窗 -->
        <el-dialog
            v-model="showConfirmDialog"
            title="提示"
            width="30%"
            align-center
        >
            <div class="confirm-message">
                是否开始上课？
            </div>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="showConfirmDialog = false">否</el-button>
                    <el-button type="primary" @click="confirmStartClass">是</el-button>
                </span>
            </template>
        </el-dialog>
    </TManageLayout>
</template>

<script setup>
import { ref, onMounted, watch,defineProps } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus';
import TimeLine from '@/components/TimeLine.vue';
import TManageLayout from '@/components/TManageLayout.vue';
import { addClassAndGet } from "@/api/lessonschedule.js"
import {useClassIdStore} from '@/stores/classId.js'
import {useCourseManageIdStore} from '@/stores/courseManageId.js'
import { addPlanService, addPlanContentsService, updatePlanService, getPlanService } from '@/api/plan';

const route = useRoute();
const router = useRouter();
const classIdStore = useClassIdStore();
const courseManageIdStore = useCourseManageIdStore();
const courseManageId= courseManageIdStore.courseManageId;

// 确认开始上课
const confirmStartClass = async () => {
    showConfirmDialog.value = false;
    const res = await addClassAndGet(courseManageId);
    console.log('上课操作响应:', res);
    classIdStore.setClassId(res.data.classId);
    console.log('classIdStore.classId:', classIdStore.classId);

    try {
        console.log('开始上课，课程ID:', courseManageId); // 添加日志
            // 跳转到聊天页面
            router.push('/teacher/chat/index');
    } catch (error) {
        ElMessage.error(error.message || '开始上课失败，请重试');
    }
};

const localSteps = ref([
    { content: '上课', completed: false },
    { content: '签到', completed: false },
    { content: '发布课堂反馈问卷', completed: false },
    { content: '布置作业', completed: false },
    { content: '上传课堂总结', completed: false },
    { content: '下课', completed: false }
]);

const initialSteps = ref(null);  // 用于存储初始步骤状态
const showSaveDialog = ref(false);
const showNameDialog = ref(false);
const planName = ref('');
const hasUnsavedChanges = ref(false);
const showConfirmDialog = ref(false);
const isStartClassPending = ref(false);

const stepOptions = ref([
    '签到',
    '布置作业',
    '发布课堂反馈问卷',
    '上传课堂总结'
]);

const addStep = () => {
    localSteps.value.splice(localSteps.value.length - 1, 0, {
        content: '签到',
        completed: false,
        customContent: ''
    });
};

const removeStep = (index) => {
    if (index !== 0 && index !== localSteps.value.length - 1) {
        localSteps.value.splice(index, 1);
    }
};

const handleStepToggle = (index) => {
    localSteps.value[index].completed = !localSteps.value[index].completed;
};

const handleSaveClick = () => {
    if (hasUnsavedChanges.value) {
        showSaveDialog.value = false;  // 关闭提示弹窗
        showNameDialog.value = true;   // 显示名称输入弹窗
    }
};

const handleSave = async () => {
  // 校验计划名称
  if (!planName.value.trim()) {
    ElMessage.warning('请输入计划名称');
    return;
  }

  try {
    // 1. 创建教学计划
    const planResponse = await addPlanService(planName.value);
    console.log('计划创建响应:', planResponse);

    // 检查计划创建是否成功
    if (planResponse.code !== 0 || !planResponse.data) {
      throw new Error('创建计划失败');
    }

    // 获取计划 ID
    const planId = planResponse.data.planId;

    // 2. 准备计划内容
    const contents = localSteps.value.map(step => ({
      content: step.content
    }));

    // 3. 添加计划内容
    const contentResponse = await addPlanContentsService(contents, planId);
    console.log('内容添加响应:', contentResponse);

    // 检查内容添加是否成功
    if (contentResponse.code !== 0) {
      throw new Error('添加计划内容失败');
    }

    // 4. 执行上课操作，获取 classId
    const classResponse = await addClassAndGet(courseManageId);
    console.log('上课操作响应:', classResponse);

    // 检查上课操作是否成功
    if (classResponse.code !== 0 || !classResponse.data?.classId) {
      throw new Error('上课操作失败');
    }

    const classId = classResponse.data.classId;
    console.log("classId4578811111111111111111111111111111",classId)

    // 5. 将计划与课程绑定
    const bindResponse = await updatePlanService(classId, planId);
    console.log('计划绑定响应:', bindResponse);

    // 检查绑定是否成功
    if (bindResponse.code !== 0) {
      throw new Error('计划绑定失败');
    }

    // 6. 保存成功
    ElMessage.success('保存成功');
    showNameDialog.value = false;

    // 更新初始状态
    initialSteps.value = JSON.stringify(localSteps.value);
    hasUnsavedChanges.value = false;

    // 重新加载计划
    await loadPlan();
  } catch (error) {
    console.error('保存教学计划失败:', error);

    // 处理特定错误
    if (error.response && error.response.status === 400) {
      ElMessage.success('保存成功');
      showNameDialog.value = false;
      initialSteps.value = JSON.stringify(localSteps.value);
      hasUnsavedChanges.value = false;
      await loadPlan();
    } else {
      ElMessage.error('保存失败，请重试');
    }
  }
};

const startClass = () => {
    if (hasUnsavedChanges.value) {
        showSaveDialog.value = true;
        isStartClassPending.value = true;
    } else {
        showConfirmDialog.value = true;
    }
};
// 处理保存提示框的确认按钮
const handleSaveDialogConfirm = () => {
    showSaveDialog.value = false;
    showNameDialog.value = true;
};

// 监听步骤变化
watch(() => JSON.stringify(localSteps.value), () => {
    checkUnsavedChanges();
}, { deep: true });

onMounted(() => {
    initialSteps.value = JSON.stringify(localSteps.value);
    loadPlan();
});

// 添加路由导航守卫
let isNavigating = false;

// 修改导航处理函数
const handleNavigation = async (path) => {
    console.log('Navigation handler called in lessonschedule with path:', path);

    if (hasUnsavedChanges.value) {
        ElMessageBox.confirm(
            '是否保存当前修改？',
            '提示',
            {
                confirmButtonText: '是',
                cancelButtonText: '否',
                type: 'warning',
            }
        )
        .then(() => {
            // 点击确认，显示输入计划名称的对话框
            showNameDialog.value = true;
        })
        .catch(() => {
            // 点击否，直接导航到课程表页面
            router.push('/teacher/manager');
        });
    } else {
        // 没有未保存的更改，直接导航
        router.push(path);
    }
};

// 处理步骤变化
const handleStepChange = (step) => {
    if (step.content === '自定义') {
        step.customContent = '';  // 清空之前的自定义内容
    }
};

// 处理输入变化
const handleInput = (step) => {
    if (step.customContent && step.customContent.trim()) {
        step.content = step.customContent.trim();
    }
};

// 处理自定义输入完成
const handleCustomInput = (step) => {
    if (step.customContent && step.customContent.trim()) {
        const customValue = step.customContent.trim();
        step.content = customValue;

        // 关闭下拉框
        const selectEl = document.querySelector('.step-select');
        if (selectEl) {
            selectEl.blur();
        }
    }
};

// 加载教学计划
const loadPlan = async () => {
    try {
        if (!classIdStore.classId) return;

        const response = await getPlanService(classIdStore.classId);
        if (response.code === 0 && response.data) {
            const plan = response.data[0]; // 获取最新的计划
            if (plan) {
                // 更新本地步骤
                localSteps.value = plan.contents.map(content => ({
                    content: content,
                    completed: false
                }));

                // 保存初始状态
                initialSteps.value = JSON.parse(JSON.stringify(localSteps.value));
            }
        }
    } catch (error) {
        console.error('加载教学计划失败:', error);
        ElMessage.error('加载计划失败，请重试');
    }
};

// 修改步骤变更检测逻辑
const checkUnsavedChanges = () => {
    if (!initialSteps.value) {
        hasUnsavedChanges.value = localSteps.value.length > 0;
        return;
    }

    const currentSteps = JSON.stringify(localSteps.value);
    hasUnsavedChanges.value = currentSteps !== initialSteps.value;
};

</script>

<style scoped>
.timeline-container {
    position: fixed;
    top: 64px;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: hidden;
    padding: 20px;
    padding-left: 80px;
}

.content-wrapper {
    display: flex;
    height: 100%;
    gap: 40px;
    max-height: calc(100vh - 104px);
}

.left-section {
    position: relative;
    flex: 1;
    display: flex;
    justify-content: flex-start;
    padding-left: 60px;
    padding-top: 0;
    margin-top: -40px;
    z-index: 1;
}

.right-section {
    flex: 1;
    display: flex;
    justify-content: flex-start;
}

.steps-editor {
    width: 100%;
    max-width: 600px;
    background-color: #fff;
    padding: 24px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
    height: calc(100vh - 180px);  /* 调整高度，留出上下边距 */
    margin-bottom: 10px;  /* 添加底部边距 */
}

.steps-container {
    flex: 1;
    overflow-y: auto;
    margin-bottom: 20px;
    max-height: calc(100% - 160px);  /* 限制最大高度，为底部按钮留出空间 */
}

.steps-list {
    padding-right: 16px;  /* 为滚动条预留空间 */
}

.bottom-actions {
    display: flex;
    justify-content: space-between;
    padding: 16px 0;
    border-top: 1px solid #e8e8e8;
    margin-top: auto;
    background-color: #fff;
}

.left-buttons {
    display: flex;
    gap: 16px;
}

.add-btn, .save-btn {
    padding: 10px 24px;  /* 增加按钮大小 */
    font-size: 16px;     /* 增加字体大小 */
    height: 40px;        /* 固定高度 */
}

.start-btn {
    padding: 10px 24px;
    font-size: 16px;
    height: 40px;
    background-color: #13227a;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: all 0.3s;
}

.start-btn:hover {
    background-color: #40a9ff;
}

.start-btn:disabled {
    background-color: #d9d9d9;
    cursor: not-allowed;
}

/* 自定义滚动条样式 */
.steps-container::-webkit-scrollbar {
    width: 6px;
}

.steps-container::-webkit-scrollbar-thumb {
    background-color: #d9d9d9;
    border-radius: 3px;
}

.steps-container::-webkit-scrollbar-track {
    background-color: #f5f5f5;
}

.main-title {
    margin: 0 0 12px 0;
    color: #333;
    font-size: 24px;
    text-align: center;
}

.editor-title {
    margin: 0 0 20px 0;
    color: #666;  /* 灰色 */
    font-size: 16px;  /* 较小的字体 */
    text-align: center;
}

.step-item {
    display: flex;
    align-items: center;
    margin-bottom: 16px;
    gap: 12px;
}

.step-number {
    width: 24px;
    height: 24px;
    background-color: #13227a;
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
}

.step-input {
    flex: 1;
    padding: 10px;
    border: 1px solid #d9d9d9;
    border-radius: 4px;
    font-size: 14px;
}

.step-input:focus {
    border-color: #13227a;
    outline: none;
    box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.delete-btn {
    width: 20px;
    height: 20px;
    padding: 0;
    background-color: transparent;
    color: #999;
    border: none;
    border-radius: 50%;
    cursor: pointer;
    font-size: 16px;
    line-height: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    transition: all 0.3s;
}

.delete-btn:hover {
    background-color: rgba(255, 77, 79, 0.1);
    color: #ff4d4f;
}

.completed .point-marker {
    background-color: #52c41a;
}

.completed .point-content {
    color: #52c41a;
}

/* 统一弹窗样式 */
:deep(.el-dialog) {
    border-radius: 8px;
    overflow: hidden;
    min-width: 420px;  /* 设置最小宽度 */
}

:deep(.el-dialog__header) {
    margin: 0;
    padding: 20px;
    border-bottom: 1px solid #f0f0f0;
    text-align: center;
}

:deep(.el-dialog__body) {
    padding: 30px 20px;
    min-height: 100px;  /* 设置最小高度 */
    display: flex;
    align-items: center;
    justify-content: center;
}

:deep(.el-dialog__footer) {
    border-top: 1px solid #f0f0f0;
    padding: 20px;
}

.save-reminder,
.confirm-message {
    font-size: 16px;
    color: #606266;
    text-align: center;
    width: 100%;
}

.dialog-header {
    font-size: 18px;
    font-weight: 500;
    color: #303133;
}

.dialog-footer {
    display: flex;
    justify-content: center;
    gap: 20px;
}

:deep(.el-input) {
    margin: 20px 0;
}

/* 保存按钮圆球样式 */
.save-bubble {
    position: absolute;
    right: 40px;
    bottom: 40px;
    width: 120px;  /* 增加圆球大小 */
    height: 120px;  /* 增加圆球大小 */
    background-color: rgba(24, 144, 255, 0.2);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    opacity: 0;
    transform: scale(0.8);
    transition: all 0.5s ease;
    box-shadow: 0 4px 12px rgba(24, 144, 255, 0.15);
    animation: bounce 2s infinite ease-in-out;  /* 添加持续跳动动画 */
}

.save-bubble.show {
    opacity: 1;
    transform: scale(1);
}

.save-text {
    color: #1890ff;
    font-size: 24px;  /* 增加文字大小 */
    opacity: 0;
    transform: translateY(10px);
    transition: all 0.3s ease 0.2s;
}

.save-bubble.show .save-text {
    opacity: 1;
    transform: translateY(0);
}

.save-bubble:hover {
    background-color: rgba(24, 144, 255, 0.3);
    animation-play-state: paused;  /* 悬停时暂停动画 */
}

/* 添加跳动动画关键帧 */
@keyframes bounce {
    0%, 100% {
        transform: scale(1) translateY(0);
    }
    50% {
        transform: scale(1.05) translateY(-10px);  /* 向上跳动并稍微放大 */
    }
}

.step-select {
    flex: 1;
    width: 100%;
}

:deep(.step-select-dropdown) {
    width: auto !important;
    min-width: 300px !important;  /* 增加最小宽度 */
}

.custom-option-content {
    display: flex;
    align-items: center;
    width: 100%;
    height: 34px;  /* 设置固定高度 */
}

.custom-label {
    white-space: nowrap;
    padding: 0 8px;
    color: #606266;
}

.custom-input {
    flex: 1;
    margin-right: 8px;  /* 添加右边距 */
}

:deep(.el-select-dropdown__item.custom-option) {
    height: 40px;  /* 增加选项高度 */
    line-height: 40px;
    padding: 0 12px;
}

:deep(.el-select-dropdown__item) {
    height: 34px;
    line-height: 34px;
}

:deep(.el-input__wrapper) {
    padding: 1px 8px !important;
    height: 32px !important;
}

:deep(.el-input__inner) {
    height: 30px !important;
    line-height: 30px !important;
}

:deep(.el-select-dropdown__list) {
    padding: 4px 0;
}

/* 确保下拉框内容完全显示 */
:deep(.el-select-dropdown) {
    transform-origin: center top !important;
    margin: 4px 0 !important;
}

/* 调整下拉框位置 */
:deep(.el-popper) {
    margin-top: 4px !important;
}
</style>
